package com.ruoyi.web.controller.app.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.exception.base.XException;
import com.ruoyi.im.domain.User;
import com.ruoyi.im.mapper.UserMapper;
import com.ruoyi.sj.domain.Nearby;
import com.ruoyi.sj.domain.WqEweiShopMember;
import com.ruoyi.sj.domain.WqEweiShopMerchUser;
import com.ruoyi.sj.mapper.WqEweiShopMemberMapper;
import com.ruoyi.sj.mapper.WqEweiShopMerchUserMapper;
import com.ruoyi.web.controller.app.im.app.service.AppUserService;
import com.ruoyi.web.controller.app.request.RequestRegisterSetPayPasswordEntity;
import com.ruoyi.web.controller.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName RegisterService
 * @Description TODO
 * @Author tyc@yanyu
 * @Date 2018/12/5 0005 11:45
 **/
@Service
public class AppRegisterService {

    @Autowired
    private WqEweiShopMemberMapper wqEweiShopMemberMapper;
    @Autowired
    private AppNearbyService appNearbyService;
    @Autowired
    private AppPersonalService appPersonalService;
    @Autowired
    private AppUserService appUserService;
    @Autowired(required = false)
    private UserMapper userMapper;//用户mapper

    @Autowired
    private WqEweiShopMerchUserMapper shopMerchUserMapper; //商户mapper
    /**
     * 发送验证码
     *
     * @param mobile
     * @param request
     * @return
     */
    public Map<String, String> sendCode(String mobile, HttpServletRequest request, String type) {
        if (StringUtils.isNotBlank(mobile)) {
            Map<String, String> map = Maps.newHashMap();
            if (PhoneUtils.getInstance().isMatcherPhone(mobile)) {
                //生成4位随机数
                String code = (int) (Math.random() * 9000 + 1000) + "";
                try {
                    JSONObject jsonOs = KxtSmsUtil.sendSms(mobile, code, type);
                    if (jsonOs.get("res_code").equals("0")) {
                        map.put("code", code);
                        request.getSession().getServletContext().setAttribute(mobile, new CodeEntity(type + "", code, new Date()));
                        return map;
                    } else {
                        throw new XException("短信发送失败，错误码：" + jsonOs.get("res_code"));
                    }
                } catch (Exception e) {
                    throw new XException("服务端错误");
                }

            } else {
                throw new XException("请输入正确的手机号");
            }
        } else {
            throw new XException("手机号不能为空");
        }
    }

    /**
     * 注册，新增用户
     *
     * @param map
     * @return
     */
    public Object doRegister(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("mobile") + "")) {
            throw new XException("手机号码不能为空");
        }
        //判断两次输入密码是否一致
        if (StringUtils.isEmpty(map.get("pwd") + "")) {
            throw new XException("密码不能为空！");
        }
        if (StringUtils.isEmpty(map.get("newPwd") + "")) {
            throw new XException("密码不能为空！");
        }
        //限定密码为6-12位
        if ((map.get("pwd") + "").trim().length() < 6 || (map.get("pwd") + "").trim().length() > 12) {
            throw new XException("请输入6~12位密码");
        }
        if (!map.get("pwd").equals(map.get("newsPwd"))) {
            throw new XException("两次输入密码不一致，请重新输入！");
        }
        //首先判断电话是否注册
        WqEweiShopMember shopMember = wqEweiShopMemberMapper.queryByPhone(map.get("mobile") + "");

        if (Integer.parseInt(map.get("type") + "") == 0) {
            if (shopMember != null) {
                throw new XException("电话已注册");
            }
            WqEweiShopMember entity = new WqEweiShopMember();
            entity.setMobile(map.get("mobile") + ""); //电话
            String pwd = map.get("pwd") + "";//密码
            entity.setPwd(EncryptionUtils.entryptPassword(pwd));  //将密码进行加密
            entity.setProvince(map.get("province") + ""); // 省
            entity.setCity(map.get("city") + "");//市
            entity.setArea(map.get("area") + "");//区
            entity.setGender(Integer.parseInt(map.get("gender") + "")); //性别
            entity.setBirthyear(map.get("birthyear") + ""); //出生年
            entity.setBirthmonth(map.get("birthmonth") + ""); //出生月
            entity.setBirthday(map.get("birthday") + ""); //出生日
            entity.setMobileverify(1);
            entity.setUniacid(2);
            if (StringUtils.isBlank(map.get("inviter") + "") || "null".equals(map.get("inviter"))) {
                entity.setInviter("0");
            } else {
                entity.setInviter(map.get("inviter") + ""); //邀请人
            }
            String openid = (long) ((Math.random() * 9 + 1) * 10000000) + "";
            entity.setOpenid(openid); //生成8位数随机ID号
            wqEweiShopMemberMapper.insertWqEweiShopMember(entity);
            String longitude = map.get("longitude") + "";
            String latitude = map.get("latitude") + "";
            Integer type = 0; //个人
            appNearbyService.insertNearby(longitude, latitude, openid, type); //存储经纬度,类型
            Map<String, String> map1 = new HashMap<>();
            map1.put("sex", map.get("sex") + "");
            map1.put("memberId", openid);
            appPersonalService.addPersonal(map1);//默认闺蜜圈资料
            int addUser = appUserService.addUser(entity);//将用户数据统一到IM中b
            return addUser;
        } else {
            if (shopMember == null) {
                throw new XException("此号码未注册，请先注册！");
            }
            String pwd = map.get("pwd") + "";
            shopMember.setPwd(EncryptionUtils.entryptPassword(pwd));
            return wqEweiShopMemberMapper.updateWqEweiShopMember(shopMember);
        }
    }

    /**
     * 校验验证码
     *
     * @param request
     * @param mobile
     * @param code
     * @param type
     * @return
     */
    public Boolean verify(HttpServletRequest request, String mobile, String code, String type) {
        if (StringUtils.isNotEmpty(code)) {
            Object attribute = request.getSession().getServletContext().getAttribute(mobile);
            if (attribute instanceof CodeEntity) {
                CodeEntity codeEntity = (CodeEntity) attribute;
                if (StringUtils.equals(codeEntity.getType(), type)) {
                    //校验验证码是否一致
                    if (StringUtils.equals(codeEntity.getCode(), code)) {
                        //判断时间是否有效
                        if (System.currentTimeMillis() - codeEntity.getDate().getTime() > 180000) {
                            throw new XException("验证码失效，请重新发送！");
                        } else {
                            return true;
                        }
                    } else {
                        throw new XException("验证码错误！");
                    }
                } else {
                    throw new XException("验证码错误！");
                }
            } else {
                throw new XException("验证码错误！");
            }
        } else {
            throw new XException("验证码不能为空！");
        }
    }

    /**
     * 用户登录
     *
     * @param mobile
     * @param pwd
     * @return
     */
    public Object login(String mobile, String pwd, String longitude, String latitude) {
        if (StringUtils.isNotEmpty(mobile)) {
            WqEweiShopMember shopMember = wqEweiShopMemberMapper.queryByPhone(mobile);
            if (shopMember != null) {
                if (StringUtils.isNotEmpty(pwd)) {
                    if (EncryptionUtils.validatePassword(pwd, shopMember.getPwd())) {
                        Nearby nearby = appNearbyService.queryByMemberId(shopMember.getOpenid());  //查询用户是否存储经纬度，第一次登录需要存储
                        if (nearby == null) {
                            Integer type = 0;
                            appNearbyService.insertNearby(longitude, latitude, shopMember.getOpenid(), type); //存储经纬度
                        } else {
                            appNearbyService.updateNearby(longitude, latitude, shopMember.getOpenid()); //不是第一次登录就更新经纬度
                        }
                        //获取IM中userId
                        User user = userMapper.selectUserByMemberId(shopMember.getOpenid());
                        shopMember.setIMID(user.getId());
                        //判断用户是否商户
                        WqEweiShopMerchUser merchUser = new WqEweiShopMerchUser();
                        merchUser.setOpenid(shopMember.getOpenid());
                        List<WqEweiShopMerchUser> merchUsers = shopMerchUserMapper.selectWqEweiShopMerchUserList(merchUser);
                        if (merchUsers==null){
                            shopMember.setIsMerchant(0);//不是商户
                        }else {
                            shopMember.setIsMerchant(1);//是商户
                        }
                        return shopMember;
                    } else {
                        throw new XException("用户名密码错误！");
                    }
                } else {
                    throw new XException("密码不能为空！");
                }
            } else {
                throw new XException("用户电话未注册！");
            }
        } else {
            throw new XException("电话不能为空！");
        }
    }

    /**
     * 修改用户资料
     *
     * @param map
     * @return
     */
    public int updateData(Map<String, String> map) {
        WqEweiShopMember shopMember = new WqEweiShopMember();
        shopMember.setProvince(map.get("province"));
        shopMember.setCity(map.get("city"));
        shopMember.setArea(map.get("area"));
        String gender = map.get("gender");
        if (StringUtils.isNotBlank(gender) && !"null".equals(gender)) {
            shopMember.setGender(Integer.valueOf(gender));
        } else {
            shopMember.setGender(2);
        }
        shopMember.setBirthyear(map.get("birthyear"));
        shopMember.setBirthmonth(map.get("birthmonth"));
        shopMember.setBirthday(map.get("birthday"));
        shopMember.setContent(map.get("content"));
        shopMember.setNickname(map.get("nickname"));
        shopMember.setAvatar(map.get("avatar"));
        shopMember.setOpenid(map.get("openid"));
        shopMember.setBackgroundPicture(map.get("backgroundPicture"));
        appUserService.updateUsers(shopMember);
        return wqEweiShopMemberMapper.updateById(shopMember);
    }

    /**
     * 设置支付密码
     */
    public Object setPayPassword(HttpServletRequest request, RequestRegisterSetPayPasswordEntity entity) {
        verify(request, entity.getPhone(), entity.getCode(), "2");
        String entryPassword = EncryptionUtils.entryptPassword(entity.getPassword());
        int updateNum = wqEweiShopMemberMapper.modifyPayPassWord(entity.getPhone(), entryPassword);
        if (updateNum != 1) throw new XException("修改失败，不存在该手机号用户！");
        return null;
    }
}
